package com.rio.dandan.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.rio.dandan.util.SessionUtils;

/**
 * ActionInterceptor
 * 
 * @作者 宋陆
 * @日期 2014年5月18日
 * @版本 1.0
 */
public class ActionInterceptor implements HandlerInterceptor {

    /** The Constant log. */
    private static final Logger log = LoggerFactory.getLogger("AI");

    /** The Constant startTime. */
    private static final ThreadLocal<Long> startTime = new ThreadLocal<Long>();

    /**
     * @see org.springframework.web.servlet.HandlerInterceptor#preHandle(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object)
     */
    public boolean preHandle(HttpServletRequest req, HttpServletResponse resp, Object handler) throws Exception {
        if (log.isInfoEnabled()) {
            log.info("|——Controller:{}, URL:{}", handler.getClass().getSimpleName(), req.getRequestURI());
            startTime.set(System.currentTimeMillis());
        }
        return true;
    }

    /**
     * @see org.springframework.web.servlet.HandlerInterceptor#postHandle(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object,
     *      org.springframework.web.servlet.ModelAndView)
     */
    public void postHandle(HttpServletRequest req, HttpServletResponse resp, Object handler, ModelAndView mv) throws Exception {
        if (log.isInfoEnabled())
            log.info("COST_TIME:{}ms ——|", System.currentTimeMillis() - startTime.get());
    }

    /**
     * @see org.springframework.web.servlet.HandlerInterceptor#afterCompletion(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object, java.lang.Exception)
     */
    public void afterCompletion(HttpServletRequest req, HttpServletResponse resp, Object handler, Exception ex) throws Exception {
        if (ex != null) {
            log.error(ex.getMessage());
            ex.printStackTrace();
        }
        SessionUtils.setSession(req.getSession());
    }

}
